﻿using Jint.Parser;
using RAP.Framework.Libary.DataSource;
using RAP.Framework.Libary.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RAP.Framework.Libary.SqlTaskParser.Parsers
{
  /// <summary>
  /// @declare解析器，Sql语句的变量定义
  /// </summary>
  public class DeclareTokenParser : TokenParserBase
  {
    internal class DeclareParams
    {
      private string[] _paramsList = null;
      public DeclareParams(string[] paramsList)
      {
        _paramsList = paramsList;
      }

      public int Length
      {
        get
        {
          return _paramsList?.Length ?? 0;
        }
      }

      public void Deconstruct(out string paramName, out string paramType, out string defaultValue)
      {
        paramName = _paramsList.First();
        paramType = _paramsList[1];
        defaultValue = _paramsList.Length >= 4 ? _paramsList[3] : "";
      }
    }
    public override void ParseToken(SqlParseContext context)
    {
      var sqlToken = context.CurrentToken;
      if (sqlToken.Param.IsNotNullOrEmpty())
      {
        var tokenParams = new DeclareParams(sqlToken.Param.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries));
        if (tokenParams.Length == 0)
        {
          return;
        }
        var (paramName, paramType, paramValue) = tokenParams;
        if (paramName.IsNullOrEmpty())
        {
          return;
        }
        var sqlGrammar = GetSqlGrammarOption(context);
        if (sqlGrammar.IsNullOrEmpty())
        {
          return;
        }
        var declareSql = string.Empty;
        switch (sqlGrammar)
        {
          case SQLGrammars.MSSQL:
            declareSql = $"declare {paramName} {paramType}{(paramValue.IsNotNullOrEmpty() ? $"={paramValue}" : "")};\n";
            break;

          case SQLGrammars.MYSQL:
            declareSql = $"set {paramName}={paramValue};\n";
            break;
        }
        ReplaceToken(context, declareSql);
      }
    }
  }
}
